package com.example.stock.ui.scan;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.example.stock.base.BaseViewModel;
import com.example.stock.model.GoodsData;
import com.example.stock.model.GoodsOrderBean;
import com.example.stock.util.DBUtil;
import com.example.stock.util.Utils;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class AutoQueryViewModel extends BaseViewModel {

    public AutoQueryViewModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<GoodsData> mBean = new MutableLiveData<>();
    public MutableLiveData<GoodsData> mHasBean = new MutableLiveData<>();

    @SuppressLint("CheckResult")
    public void query(GoodsOrderBean orderBean, final GoodsData code) {
        Observable.just(1).map(new Function<Integer, List<GoodsData>>() {
            @NonNull
            @Override
            public List<GoodsData> apply(@NonNull Integer integer) throws Exception {
                return DBUtil.getInstance().queryGoodsDataByCode(orderBean, code);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<GoodsData>>() {
                    @Override
                    public void accept(@NonNull List<GoodsData> goodsData) throws Exception {
                        if (goodsData.size() > 0) {
                            GoodsData data = goodsData.get(0);
                            double oriSl = TextUtils.isEmpty(data.getSl()) ? 0L : Double.parseDouble(data.getSl());
                            double newSl = TextUtils.isEmpty(code.getSl()) ? 0L : Double.parseDouble(code.getSl());
                            double res = oriSl + newSl;
                            data.setSl(res + "");
                            data.setPcCode(code.getPcCode());
                            data.setGysName(code.getGysName());
                            mBean.setValue(data);
                        } else {
                            mBean.setValue(null);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        mBean.setValue(null);
                        Utils.getInstance().showToast("e : " + throwable.getMessage());
                        Log.d("wyj", "e : "+ throwable.getMessage());
                    }
                });
    }
}
